package ar.edu.itba.it.pdc.app;

import java.io.IOException;

import org.apache.log4j.Logger;

import ar.edu.itba.it.pdc.app.admin.AdministrationService;
import ar.edu.itba.it.pdc.app.config.ProxySettings;
import ar.edu.itba.it.pdc.app.config.impl.ProxySettingsXMLImpl;
import ar.edu.itba.it.pdc.app.config.mapping.Settings;
import ar.edu.itba.it.pdc.proxy.POP3Proxy;

public class Madonna3 {
	
	public final static Logger log = Logger.getRootLogger();

	private static Madonna3 instance;
	
	public static void main(String[] args) {
		try {
			instance = new Madonna3();
			instance.start();
		} catch (Exception e) {
			log.debug(e.getMessage());
			log.fatal("Madonna3 can't start to sing");
			System.exit(1);
		}
	}

	public static Madonna3 getApp() {
		return instance;
	}
	
	
	private final ProxySettings proxySettings;
	private AdministrationService administrationService;
	private POP3Proxy proxy;
	private Settings settings;
	
	public Madonna3() {
		ProxySettings ps = new ProxySettingsXMLImpl();
		ps.setPathFile("config/settings.xml");
		this.proxySettings = ps;
		this.settings = proxySettings.loadSettings();
	}
	
	public void start() throws IOException {
		//Service instanciation
		this.administrationService = new AdministrationService(settings.getAdmin().getPort(), settings.getAdmin().getBacklog());
		this.proxy = new POP3Proxy(settings.getProxy().getPort(), settings.getProxy().getBacklog());
		
		//Go go go!
		new Thread(this.administrationService).start();
		this.proxy.start();
	}

	public Settings getSettings() {
		return settings;
	}
	
	public synchronized void setSettings(Settings newSettings) {
		this.settings = newSettings;
	}
	
	public void persistSettings() {
		this.proxySettings.saveSettings(settings);
	}

	public static Logger getLog() {
		return log;
	}

	public ProxySettings getProxySettings() {
		return proxySettings;
	}

	public AdministrationService getAdministrationService() {
		return administrationService;
	}

	public POP3Proxy getProxy() {
		return proxy;
	}
	
}
